import functools

from flask import current_app
from flask import g
from flask import session, jsonify

from ihome.models import User
from ihome.utils.response_code import RET, error_map


def check(func):
    @functools.wraps(func)
    def inner_func(*args, **kwargs):
        user_id = session.get('user_id')
        user = None
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        if user:
            g.user = user

            return func(*args, **kwargs)
        else:
            return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

            # return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data={'name': name, 'user_id': user_id, 'mobile': mobile})

    return inner_func


def file_upload(data):
    """
    上传文件到七牛云
    :param data: 上传的数据
    :return: 生成随机文件名
    """

    import qiniu
    # access_key = "kJ8wVO7lmFGsdvtI5M7eQDEJ1eT3Vrygb4SmR00E"
    # secret_key = "rGwHyAvnlLK7rU4htRpNYzpuz0OHJKzX2O1LWTNl"
    # bucket_name = "infonews"  # 存储空间名称




    access_key = "NpPQF3Pi9ZeDu00HKXSnqpO_WQHakqsuZmTox4Dn"
    secret_key = "V_w4KVhLe3hSrAR54PU27m-0OnPPGQIFJlXcQW20"
    bucket_name = "newhouse1"  # 存储空间名称

    q = qiniu.Auth(access_key, secret_key)
    key = None  # 设置文件名, 如果为None则生成随机文件名
    token = q.upload_token(bucket_name)
    # 上传文件
    ret, info = qiniu.put_data(token, key, data)
    if ret is not None:  # 上传成功
        return ret.get("key")  # 取出随机的文件名
    else:
        raise BaseException(info) # error message in info